import bs4

# 构造一个BS对象
with open("./example.html", "r") as fp:
    b = bs4.BeautifulSoup(fp.read(), features='lxml')
    type(b)
    # 通过 "."操作符访问子节点
    # title = b.head.title
    # assert isinstance(title, bs4.element.Tag)
    # print(title.name)
    # print(title.attrs)
    # print(title.text)

    # 访问子节点或孙子节点
    # tbody = b.body.form.table.tbody
    # 遍历子节点(方式一)
    # type(tbody)
    # assert isinstance(tbody, bs4.element.Tag)
    # for p in tbody.children:
    #     # if isinstance(p, bs4.element.NavigableString):
    #     #     continue
    #     #
    #     if isinstance(p, bs4.element.Tag):
    #         print(type(p.children))
    #         children = list(p.children)
    #         print(children[0].text, children[1].text)

    # 节点的遍历 (方式二）
    # for p in tbody.contents:
    #     if isinstance(p, bs4.element.NavigableString):
    #         continue
    #
    #     print(p.contents[0].text, p.contents[1].text)
    # print(tbody.contents)


    # 遍历节点与孙子节点
    # print("访问子节点与孙子节点")
    # table = b.body.form.table
    # for p in tbody.descendants:
    #     if isinstance(p, bs4.element.NavigableString):
    #         print("-")
    #     else:
    #         print(p.name)

        # print(type(p))
        # print(p)

    # span = b.body.form.span
    # for s in span.strings:
    #     print(s)


    # 访问字符串
    # form = b.body.form
    # for s in form.stripped_strings:
    #     # print(type(s))
    #     print(s)

    # # 访问兄弟节点
    tr = b.body.form.table.tbody.tr
    assert isinstance(tr, bs4.element.Tag)
    #
    # # 遍历所有的兄弟节点
    # for s in tr.next_siblings:
    #     print("type={} value={}".format(type(s), s))

    # 访问后面的元素
    # print(tr.next_element.next_element.text)
    # print(tr.next_elements)
    # for s in tr.next_elements:
    #     print(s)